package com.xxxx.server.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxxx.server.mapper.RoleMapper;
import com.xxxx.server.pojo.Menu;
import com.xxxx.server.pojo.MenuRole;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.pojo.Role;
import com.xxxx.server.service.IMenuRoleService;
import com.xxxx.server.service.IMenuService;
import com.xxxx.server.service.IRoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/basic/permiss")
public class PermissController {
    @Autowired
    private IMenuRoleService menuRoleService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IRoleService roleService;
    @Autowired

    @ApiOperation("查询所有角色")
    @GetMapping("/")
    public List<Role> getallrole(){
        return roleService.list();
    }

 /*   @ApiOperation("修改角色")
    @PutMapping("/role")
    public RespBean update(@RequestBody Role role){
        if (roleService.updateById(role)){
            return RespBean.success("更新成功");
        }else{
            return RespBean.error("更新失败");
        }
    }*/

    @ApiOperation("删除角色")
    @DeleteMapping("/role/{id}")
    public RespBean deleterole(@PathVariable("id") Integer id){
        if (roleService.removeById(id)){
            return RespBean.success("删除成功");
        }else{
            return RespBean.error("删除失败");
        }
    }

    @ApiOperation("添加角色")
    @PostMapping("/role")
    public RespBean addrole(@RequestBody Role role){
        if (!role.getName().startsWith("Role_")){
            // // 角色必须以`ROLE_`开头，数据库中没有，则在这里加
            role.setName("ROLE_"+role.getName());
        }
        if (roleService.save(role)){
            return RespBean.success("添加成功");
        }else{
            return RespBean.error("添加失败");
        }
    }

    @ApiOperation("批量删除角色")
    @DeleteMapping("/role")
    public RespBean deletesrole(Integer[] ids){
        if (roleService.removeByIds(Arrays.asList(ids))){
            return RespBean.success("删除成功");
        }else {
            return RespBean.error("删除失败");
        }
    }

    @ApiOperation("更新菜单角色")
    @PutMapping("/role")
    public RespBean updatemenurole(Integer rid,Integer[] mids){
      return menuRoleService.deletemenurole(rid,mids);
    }

    @ApiOperation("查询所有菜单")
    @GetMapping("/menus")
    public List<Menu> getAllMenus(){
        return menuService.getAllMenus();
    }


    @ApiOperation("根据角色id查询菜单id")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMidByRid(@PathVariable Integer rid){
        return menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid",rid)).stream()
                .map(MenuRole::getMid).collect(Collectors.toList());
    }

}
